package com.videoStream.video.m3u8;

import java.io.File;
import java.util.Base64;

/**
 * @Author: wwy
 * @Date: 2022/7/14 11:08
 */
public class DefaultM3u8Build implements BuildM3u8 {
    private String ip;
    private String cameraIp;
    private short port;
    private String m3u8FilePath;

    public DefaultM3u8Build(String ip, String cameraIp, short port, String m3u8FilePath) {
        this.ip = ip;
        this.cameraIp = cameraIp;
        this.port = port;
        this.m3u8FilePath = m3u8FilePath;
    }

    /**
     * m3u8 上传地址
     * @return
     */
    @Override
    public String buildM3u8() {

        Base64.Encoder encoder = Base64.getEncoder();
        String m3u8Path = encoder.encodeToString(cameraIp.getBytes());
        String m3u8File = "/"+m3u8Path+"/live.m3u8";
        StringBuilder m3u8Builder = new StringBuilder();
        m3u8Builder.append("http://")
                .append(ip)
                .append(":")
                .append(port)
                .append("/upload")
                .append(m3u8File);
        String m3u8TsFile = m3u8FilePath+"\\"+m3u8Path;
        File file = new File(m3u8TsFile);
        if(file.exists()){
            //进行删除
            File[] files = file.listFiles();
            for (File file1 : files) {
                file1.delete();
            }
        }
        return m3u8Builder.toString();
    }

    /**
     * m3u8  ts模板地址
     * @return
     */
    @Override
    public String buildM3u8Template() {
        Base64.Encoder encoder = Base64.getEncoder();
        String m3u8Path = encoder.encodeToString(ip.getBytes());
        StringBuilder m3u8FileTemplateBuilder = new StringBuilder();
        m3u8FileTemplateBuilder.append("http://")
                .append(ip)
                .append(":")
                .append(port)
                .append("/upload/")
                .append(m3u8Path)
                .append("/live-%d.ts");

        return m3u8FileTemplateBuilder.toString();
    }

    /**
     * m3u8 播放地址
     * @return
     */
    @Override
    public String buildM3u8Live() {
        Base64.Encoder encoder = Base64.getEncoder();
        String m3u8FilePath = encoder.encodeToString(cameraIp.getBytes());
        String m3u8File = "/"+m3u8FilePath+"/live.m3u8";
        StringBuilder m3u8LiveBuilder = new StringBuilder();
        m3u8LiveBuilder.append("http://")
                .append(ip)
                .append(":")
                .append(port)
                .append("/video")
                .append(m3u8File);
        return m3u8LiveBuilder.toString();
    }
}
